package com.tarena.lbs.user.service.impl;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.encoder.JwtEncoder;
import com.tarena.lbs.user.dao.repository.AdminRepository;
import com.tarena.lbs.user.pojo.param.AdminParam;
import com.tarena.lbs.user.pojo.po.AdminPO;
import com.tarena.lbs.user.pojo.query.AdminQuery;
import com.tarena.lbs.user.pojo.vo.AdminVO;
import com.tarena.lbs.user.service.AdminService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private JwtEncoder<Map> jwtEncoder;

    @Autowired
    private AdminRepository adminRepository;

    @Override
    public AdminVO getAdminDetail(String token) throws BusinessException {
        log.info("service层");
        Map<String, Object> loginFromToken = jwtEncoder.getLoginFromToken(token, Map.class);
        Integer id = (Integer) loginFromToken.get("id");
        AdminPO adminPO = adminRepository.findById(id);
        AdminVO adminVO = new AdminVO();
        BeanUtils.copyProperties(adminPO, adminVO);
        return adminVO;
    }

    @Override
    public List<AdminVO> selectList(AdminQuery query) {
        log.info("Service层查询账号列表");

        // 构建查询条件
        QueryWrapper<AdminPO> queryWrapper = buildQueryWrapper(query);

        // 执行查询
        List<AdminPO> adminPOs = adminRepository.findList(queryWrapper);

        // 转换为VO
        return adminPOs.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    // 构建查询条件的公共方法
    private QueryWrapper<AdminPO> buildQueryWrapper(AdminQuery query) {
        QueryWrapper<AdminPO> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(query.getNickname())) {
            queryWrapper.like("nickname", query.getNickname());
        }
        if (StringUtils.isNotBlank(query.getAccountPhone())) {
            queryWrapper.like("account_phone", query.getAccountPhone());
        }
        return queryWrapper;
    }

    // PO转VO的公共方法
    private AdminVO convertToVO(AdminPO po) {
        AdminVO vo = new AdminVO();
        BeanUtils.copyProperties(po, vo);
        return vo;
    }
    @Override
    public void saveAdmin(AdminParam param) {
        // 实现保存逻辑
    }
}